package com.itheima.health.interceptor;

import com.itheima.health.context.BaseContext;
import com.itheima.health.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


@Component
@Slf4j
public class LoginMemberlnterceptor implements HandlerInterceptor {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       if (handler instanceof HandlerMethod){
           //controller方法才处理
           HttpSession session=request.getSession();
//        //登录成功将存入session
//           String loginUserInfo=stringRedisTemplate.opsForValue().get("LOGINUSER");
//           if (null==loginUserInfo){
//               //响应401  用户没有登录
//               response.setStatus(HttpStatus.UNAUTHORIZED.value());
//               return false;
//           }


          User loginUser=(User)session.getAttribute("loginUser");
          if (null==loginUser){
              //响应401  用户没有登录
              response.setStatus(HttpStatus.UNAUTHORIZED.value());
              return false;
          }
          //把登录用户存入threaLocal
           Integer loginUserId=loginUser.getId();
           BaseContext.setCurrentId(loginUserId);

       }
        //非controller方法放行
        return true;
    }
    //重写请求方法
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContext.removeCurrentId();
    }
}
